package com.ruoyi.driver.ocrUtil;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.*;

/**
 * HTTP POST请求工具类，对应PHP的request_post和request_posts函数
 */
public class HttpPostUtil {

    /**
     * 发送POST请求（不验证SSL证书，对应request_posts函数）
     * @param url 请求URL
     * @param param 请求参数（JSON字符串）
     * @return 响应结果
     */
    public static String requestPosts(String url, String param) {
        if (url == null || url.isEmpty() || param == null || param.isEmpty()) {
            return null;
        }
        
        HttpsURLConnection connection = null;
        BufferedReader reader = null;
        OutputStream os = null;
        
        try {
            // 创建URL对象
            URL requestUrl = new URL(url);
            
            // 信任所有证书（对应PHP的CURLOPT_SSL_VERIFYPEER=false）
            SSLContext sslContext = SSLContext.getInstance("TLS");
            TrustManager[] trustAllCerts = new TrustManager[]{
                new X509TrustManager() {
                    public X509Certificate[] getAcceptedIssuers() {
                        return null;
                    }
                    public void checkClientTrusted(X509Certificate[] certs, String authType) throws CertificateException {}
                    public void checkServerTrusted(X509Certificate[] certs, String authType) throws CertificateException {}
                }
            };
            sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
            HttpsURLConnection.setDefaultHostnameVerifier((hostname, session) -> true);
            
            // 打开连接
            connection = (HttpsURLConnection) requestUrl.openConnection();
            
            // 设置请求方法
            connection.setRequestMethod("POST");
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setUseCaches(false);
            
            // 设置请求头
            connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
            connection.setRequestProperty("Connection", "Keep-Alive");
            connection.setRequestProperty("Charset", "UTF-8");
            
            // 发送请求参数
            os = connection.getOutputStream();
            os.write(param.getBytes("UTF-8"));
            os.flush();
            
            // 读取响应
            if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                reader = new BufferedReader(new InputStreamReader(
                        connection.getInputStream(), "UTF-8"));
                StringBuilder result = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    result.append(line);
                }
                return result.toString();
            } else {
                // 读取错误响应
                reader = new BufferedReader(new InputStreamReader(
                        connection.getErrorStream(), "UTF-8"));
                StringBuilder error = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    error.append(line);
                }
                System.err.println("请求失败: " + error.toString());
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            // 关闭资源
            try {
                if (os != null) os.close();
                if (reader != null) reader.close();
                if (connection != null) connection.disconnect();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 发送POST请求（验证SSL证书，对应request_post函数）
     * @param url 请求URL
     * @param param 请求参数（JSON字符串）
     * @return 响应结果
     */
    public static String requestPost(String url, String param) {
        if (url == null || url.isEmpty() || param == null || param.isEmpty()) {
            return null;
        }
        
        HttpURLConnection connection = null;
        BufferedReader reader = null;
        OutputStream os = null;
        
        try {
            // 创建URL对象
            URL requestUrl = new URL(url);
            
            // 打开连接
            connection = (HttpURLConnection) requestUrl.openConnection();
            
            // 设置请求方法
            connection.setRequestMethod("POST");
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setUseCaches(false);
            
            // 设置请求头
            connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
            connection.setRequestProperty("Connection", "Keep-Alive");
            connection.setRequestProperty("Charset", "UTF-8");
            
            // 发送请求参数
            os = connection.getOutputStream();
            os.write(param.getBytes("UTF-8"));
            os.flush();
            
            // 读取响应
            if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                reader = new BufferedReader(new InputStreamReader(
                        connection.getInputStream(), "UTF-8"));
                StringBuilder result = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    result.append(line);
                }
                return result.toString();
            } else {
                // 读取错误响应
                reader = new BufferedReader(new InputStreamReader(
                        connection.getErrorStream(), "UTF-8"));
                StringBuilder error = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    error.append(line);
                }
                System.err.println("请求失败: " + error.toString());
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            // 关闭资源
            try {
                if (os != null) os.close();
                if (reader != null) reader.close();
                if (connection != null) connection.disconnect();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
